package com.raychi.demo.action;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
import com.raychi.demo.entity.Buyer;
import com.raychi.demo.service.BuyerService;
import com.raychi.demo.util.BuyerUtil;
import com.raychi.demo.util.JdbcUtil;

public class BuyerAction  extends ActionSupport{

	private static final long serialVersionUID = 1L;
	
	private List<Buyer> list;
	private Buyer buyer;
	private BuyerService buyerService;

	public String list() throws ClassNotFoundException, SQLException{
		list = buyerService.getBuyers();
		return "list";
	}
	
	public String input(){
		
		return "input";
	}
	public String save() throws ClassNotFoundException, SQLException{
		buyerService.save(buyer);
		return list();
	}
	
	
	public String delete() throws ClassNotFoundException, SQLException{
		buyerService.delete(buyer);
		return list();
	} 
	
	public String edit(){
		
		return "edit";
	}
	
	public String update() throws ClassNotFoundException, SQLException{
		buyerService.update(buyer);
		return list();
	}
	
	
	public Buyer getBuyerById(int id) {
		Buyer buyer = null;
		Connection conn = null;
		try {
			conn = JdbcUtil.getConnection();
			Statement st = conn.createStatement();
			String sql = "select * from buyer where id=" + id;
			ResultSet rs = st.executeQuery(sql);
			while (rs.next()) {
				buyer = BuyerUtil.createBuyer(rs);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
		return buyer;
		
	}

	public List<Buyer> getList() {
		return list;
	}

	public void setList(List<Buyer> list) {
		this.list = list;
	}

	public Buyer getBuyer() {
		return buyer;
	}

	public void setBuyer(Buyer buyer) {
		this.buyer = buyer;
	}
	public void setBuyerService(BuyerService buyerService) {
		this.buyerService = buyerService;
	}
}
